import React, { Component } from 'react';
import { jsonPost } from '@/helpers/request';
import apiConfig from '@/apiConfig';
import { Modal, Button, Input, Form, Icon, Row, Col, message } from 'antd';
import isFunction from 'lodash/isFunction';
import isEmpty from 'lodash/isEmpty';

const FormItem = Form.Item;

class CaptchaProp extends Component {

  constructor(props) {
    super(props);
    this.state = {
      validatingPhone: false,
      visible: false,
      isShowModal: false,
      count: props.countDown,
      isModal: props.isModal,
      btnText: props.getCaptchaButtonText,
    };
  }

  /**
   * 倒数
   */
  cbInterval = () => {
    this.setState({
      visible: true,
    });
    let interval = window.setInterval(() => {
      if (interval) {
        let tempCount = this.state.count;
        if (1 == tempCount) {
          this.setState({
            visible: false,
            count: 60,
            btnText: '获取验证码',
          });
          interval = null;
        } else {
          --tempCount;
          this.setState({
            count: tempCount,
            btnText: `${tempCount} ${this.props.getCaptchaSecondText}`,
          });
        }
      }
    }, 1000);
  };

  onGetCaptcha = () => {
    const { form, mobileFieldName } = this.props;
    form.validateFields([mobileFieldName], {}, (err, values) => {
      if (isEmpty(err)) {
        if (this.state.isModal) {
          this.setState({
            isShowModal: true,
          });
        }
        false == this.props.isModal &&
        this.fetchCode(values[mobileFieldName]);
      }
    });
  };

  fetchCode(mobile) {
    return jsonPost(apiConfig.sendCaptcha, {}, {
      params: {
        phone: mobile,
        type: this.props.getCaptchaType,
      },
    }).then(rsp => {
      if (rsp && rsp.status && (200 == rsp.status || 1 == rsp.status)) {
        isFunction(this.cbInterval) && this.cbInterval();
        message.success('验证码已发送,请留意手机短信');
      } else {
        if (rsp && typeof rsp.data != 'undefined') {
          message.error(rsp.data || rsp.msg || '操作失败，请稍后重试');
        }
      }
    });
  }

  handleOk = () => {
    if (this.state.isModal) {
      //获取图形验证码
      this.setState({
        isShowModal: false,
      });
    }

  };

  handleCancel = () => {
    if (this.state.isModal) {
      //获取图形验证码
      this.setState({
        isShowModal: false,
      });
    }
  };

  render() {
    const {
        form,
        size,

        mobileFieldName,
        mobileItemProps = {},
        mobileRules = [],
        mobileInput,
        mobileOptions = {},

        captchaFieldName,
        captchaItemProps = {},
        captchaOptions = {},
      } = this.props,
      { isModal, isShowModal, btnText, visible } = this.state;
    const { getFieldDecorator } = form;

    return (
      <React.Fragment>
        <FormItem {...mobileItemProps} hasFeedback>
          {getFieldDecorator(mobileFieldName, {
            validateFirst: true,
            rules: [
              { required: true, message: '请输入手机号' },
              { pattern: /^1\d{10}$/, message: '请输入正确的手机号' },
              ...mobileRules,
            ],
            ...mobileOptions,
          })(
            mobileInput ? mobileInput :
              <Input size={size}
                     prefix={<Icon type="mobile" style={{ color: 'rgba(0,0,0,.25)' }}/>}
                     autoComplete={'on'}
                     placeholder="手机号"/>,
          )}
        </FormItem>
        <FormItem {...captchaItemProps}>
          <Row gutter={8}>
            <Col span={16}>
              {getFieldDecorator(captchaFieldName, {
                validateFirst: true,
                rules: [
                  { required: true, message: '请输入验证码' },
                ],
                ...captchaOptions,
              })(
                <Input placeholder="输入验证码" size={size} autoComplete={'off'}/>,
              )}
            </Col>
            <Col span={8}>
              <Button
                size={size}
                disabled={visible}
                onClick={this.onGetCaptcha.bind(this)}
                className={this.props.getCodeBtnClass}>{btnText}</Button>
            </Col>
          </Row>
        </FormItem>
        {isModal && <Modal
          title="图形验证"
          visible={isShowModal}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okButtonProps={{ disabled: false }}
          cancelButtonProps={{ disabled: false }}
        >
          <p>请输入图形验证码</p>
          <p><Input placeholder="请输入验证码" allowClear autocomplete={'off'}/></p>
        </Modal>}

      </React.Fragment>
    );
  }
}

CaptchaProp.defaultProps = {
  getCodeBtnClass: '',
  countDown: 60,
  mobileFieldName: 'mobile',
  captchaFieldName: 'captcha',
  isModal: false,
  getCaptchaType: 1, //type 短信类型{0:登录,1:注册}
  getCaptchaButtonText: '获取验证码',
  getCaptchaSecondText: '秒',
  size: 'default',
};
export default CaptchaProp;
